import 'package:flutter/material.dart';
import 'package:flutter_fitness/app_controller.dart';
import 'package:flutter_fitness/const.dart';
import 'package:flutter_fitness/model/db/record_provider.dart';
import 'package:flutter_fitness/model/db/user_provider.dart';
import 'package:flutter_fitness/model/entity/record.dart';
import 'package:flutter_fitness/model/entity/user.dart';
import 'package:flutter_fitness/pages/main/main_view.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginLogic extends GetxController {
  TextEditingController textEditingController;

  @override
  void onInit() {
    super.onInit();
    textEditingController = TextEditingController();
  }

  void onEnter() {
    final user = User();
    user.username = textEditingController.text;
    final provider = UserProvider();
    provider.open().then((value) async {
      final saveUser = await provider.insert(user);
      if (saveUser.id != null) {
        final pref = await SharedPreferences.getInstance();
        pref.setInt(TAG_LOGIN_ID, saveUser.id);
        provider.close();
        final recordProvider = RecordProvider();
        await recordProvider.open();
        final dateTime = DateTime.now();
        Record record = await recordProvider.getRecordByUserIdAndTime(
            saveUser.id, dateTime.year, dateTime.month, dateTime.day);
        if (record == null)
          record = Record(
              userId: saveUser.id,
              year: dateTime.year,
              month: dateTime.month,
              day: dateTime.day);
        final appController = Get.find<AppController>();
        appController.user.value = saveUser;
        appController.record.value = record;
        Get.off(() => MainPage());
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    textEditingController.dispose();
  }
}
